package com.beidouin.sensortest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.HardWare.ADXL345;
import com.friendlyarm.AndroidSDK.FileCtlEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;

import static com.HardWare.ADXL345.ADXL345_Init;

public class AccelerometerActivity extends AppCompatActivity implements Runnable{

    TextView x_val,y_val,z_val;
    int devFD=-1;
    Handler handler;
    Thread t = new Thread(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accelerometer);

        x_val= (TextView) findViewById(R.id.X_val);
        y_val= (TextView) findViewById(R.id.Y_val);
        z_val= (TextView) findViewById(R.id.Z_val);

        devFD = HardwareControler.open("/dev/i2c-0", FileCtlEnum.O_RDWR);
        ADXL345_Init(devFD);
        //x_val.setText(ADXL345_Init(devFD)+" ");


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x101) {
                    x_val.setText(msg.getData().getDouble("data0")+"g");
                    y_val.setText(msg.getData().getDouble("data1")+"g");
                    z_val.setText(msg.getData().getDouble("data2")+"g");
                }
                super.handleMessage(msg);
            }
        };
        t.start();
    }

    @Override
    protected void onDestroy() {
        //将线程销毁掉
        t.interrupt();
        HardwareControler.close(devFD);
        super.onDestroy();
    }


    public void run() {
        while (!Thread.currentThread().isInterrupted())
        {
            Message m=handler.obtainMessage();
            double[] data;
            data= ADXL345.get_acceleration(devFD);
            for(int i=0;i<3;i++)
            {
                data[i]= (double)Math.round(data[i]*1000)/1000;
            }
            m.what=0x101;
            Bundle bundle =new Bundle();
            bundle.putDouble("data0",data[0]);
            bundle.putDouble("data1",data[1]);
            bundle.putDouble("data2",data[2]);

            m.setData(bundle);
            handler.sendMessage(m);
            try{
                Thread.sleep(500);}
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
